<?php
namespace App\Admin\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\ApiResponseService;
use App\Services\OrderAnalysisService;
use Carbon\Carbon;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;
use Illuminate\Support\HtmlString;

class ChartDataController extends Controller
{
    protected $analysisService;

    public function __construct(OrderAnalysisService $analysisService)
    {
        $this->analysisService = $analysisService;
    }

    public function getPaymentsAnalysis()
    {

    }

    public function getFinanceLineData(Request $request)
    {
        $postData = $this->postDataFilter($request);
        $data = $this->analysisService->getFinanceLineData($postData);
        return ApiResponseService::returnData($data);
    }

    public function getOrderLineData(Request $request)
    {
        $postData = $this->postDataFilter($request);
        $data = $this->analysisService->getOrderLineData($postData);
        return ApiResponseService::returnData($data);
    }

    public function getPaymentsTableData(Request $request)
    {
        $postData = $this->postDataFilter($request);
        $data = $this->analysisService->getPaymentsTableData($postData);
        return response()->json($data);
    }

    public function getInterfacesTableData(Request $request)
    {
        $postData = $this->postDataFilter($request);
        $data = $this->analysisService->getInterfacesTableData($postData);
        return new HtmlString($data);
    }

    protected function postDataFilter(Request $request)
    {
        $staticRange = $request->input('staticRange', -1);
        $start_at = $request->input('start_at', Carbon::now()->startOfDay()->toDateTimeString());
        $end_at = $request->input('end_at', Carbon::now()->toDateTimeString());
        if ($staticRange == 1) {
            $start_at = Carbon::now()->startOfWeek()->toDateTimeString();
            $end_at = Carbon::now()->toDateTimeString();
        } elseif ($staticRange == 2) {
            $start_at = Carbon::now()->startOfMonth()->toDateTimeString();
            $end_at = Carbon::now()->toDateTimeString();
        } elseif ($staticRange == 3) {
            $start_at = Carbon::now()->subMonth(3)->startOfMonth()->toDateTimeString();
            $end_at = Carbon::now()->toDateTimeString();
        }

        $postData = [
            'accuracy' => $request->input('accuracy', 1),
            'mchInfo' => $request->input('mchInfo', null),
            'start_at' => $start_at,
            'end_at' => $end_at,
            'staticRange' => $staticRange
        ];
        return $postData;
    }
}
